/* eslint-disable no-shadow */
/* eslint-disable no-unused-vars */
import React, { memo, useState, useEffect, useCallback } from "react";
import Taro, {
  useRouter,
  useDidShow
} from "@tarojs/taro";
import { useSelector, useDispatch, shallowEqual } from "react-redux";
import { updateState } from "@/store/actions/global";
import { View } from "@tarojs/components";
import { Loading, Empty } from "@antmjs/vantui";
import debounce from "lodash/debounce";
import Authorization from "@/components/Authorization";
import Navbar from "@/components/Navbar"
import RecipeItem from "@/components/RecipeItem";
import BackTop from "@/components/BackTop";
import { themeColor } from "../../utils/config";
import "./index.less";

const Index = () => {
  const router = useRouter();
  const dispatch = useDispatch();
  const { globalData } = useSelector(
    (state) => ({ globalData: state.globalData }),
    shallowEqual
  );
  const { isLogin, showBackTop } = globalData;
  const [List, setList] = useState([]);
  const handleClick = useCallback(
    debounce(
      (type, id, username) => {
        console.log("CLICK", type, id);
        let url = "";
        if (type === "recipe") {
          url = "/pages/recipeInfo/index?recipe_id=" + id;
        }
        if (type === "user") {
          url = `/pages/userCenter/index?user_id=${id}&username=${username}`;
        }
        if (!isLogin) {
          dispatch(
            updateState({
              isShowGrant: true,
            })
          );
        } else {
          jumpTo(url);
        }
      },
      500,
      {
        leading: true,
        trailing: false,
      }
    ),
    [isLogin]
  );
  const jumpTo = (url) => {
    Taro.navigateTo({
      url,
    });
  };

  const getListDom = (type = 1) => {
    return List.map((item, index) => {
      return (
        <RecipeItem
          key={item.recipe_id}
          data={item}
          handleClick={handleClick}
        ></RecipeItem>
      );
    });
  };
  useEffect(() => {
    if (!isLogin) {
      dispatch(
        updateState({
          isShowGrant: true,
        })
      );
      return;
    }
  }, [isLogin, dispatch]);
  useDidShow(() => {
    if (isLogin) {
      const history = Taro.getStorageSync("history");
      setList(history);
    }
  });

  return (
    <View className='history'>
      <Authorization canClose={false}></Authorization>
      <Navbar title='历史浏览' arrow='true'></Navbar>
      {showBackTop ? <BackTop /> : null}
      <View className='m-result'>
        {!List.length ? <Empty description='暂无菜谱' /> : (getListDom())}
      </View>
    </View>
  );
};

export default memo(Index);
